package com.shhm.config;

import com.github.benmanes.caffeine.cache.Cache;
import com.shhm.common.entity.system.SysPassAuth;
import com.shhm.common.mapper.AuthWhiteMapper;
import com.shhm.common.mapper.SysRoleOperatePermsMapper;
import com.shhm.common.entity.admin.SysRoleOperatePerms;
import com.shhm.common.utils.LocalCacheUtil;
import com.shhm.common.utils.RedisUtil;
import com.shhm.common.utils.SysPermsUtil;
import jakarta.annotation.Resource;
import org.springframework.boot.CommandLineRunner;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author JackZ
 * @version 1.0
 * @description: TODO
 * @date 2025/7/13 上午12:12
 */
@Component
public class SecondHandHiveMallInitializer implements CommandLineRunner {
    @Resource
    private SysRoleOperatePermsMapper sysRoleOperatePermsMapper;
    @Resource
    private RedisTemplate<String, String> redisTemplate;
    @Resource(name = "PermissionsCache")
    private Cache<String, List<SysRoleOperatePerms>> localPermissionsCache;
    @Resource(name = "WhiteListCache")
    private Cache<String, List<SysPassAuth>> localSysPassAuthCache;
    @Resource
    private AuthWhiteMapper authWhiteMapper;

    @Override
    public void run(String... args) {
        /**
         * 将权限字符存入本地缓存和redis
         */
        SysPermsUtil.flushOperatePermsCache(localPermissionsCache,redisTemplate,sysRoleOperatePermsMapper);
//        List<SysRoleOperatePerms> list = sysRoleOperatePermsMapper.selectList(null);
//        RedisUtil.flushSysRoleOperatePerms(list,redisTemplate);
//        Map<String, List<SysRoleOperatePerms>> roleOpeMap = list.stream().collect(Collectors.groupingBy(SysRoleOperatePerms::getRoleKey));
//        roleOpeMap.forEach((k,v)->localPermissionsCache.put(LocalCacheUtil.CACHE_PERMS_KEY_PREFIX+k,v));
        //        Executors.newVirtualThreadPerTaskExecutor()
        /**
         * 将过滤器白名单存入本地缓存和redis
         */
//        List<SysPassAuth> whiteAuthList = authWhiteMapper.selectList(null);
//        RedisUtil.flushSysAuthWhite(redisTemplate,whiteAuthList);
//        Map<String, List<SysPassAuth>> passAuthMap = whiteAuthList.stream().collect(Collectors.groupingBy(SysPassAuth::getAuthKey));
//        passAuthMap.forEach((k,v)->localSysPassAuthCache.put(LocalCacheUtil.CACHE_AUTH_KEY_PREFIX+k,v));

        System.out.println("======= Initialized success! Welcome to SecondHandHiveMall! =======");
    }
}
